package com.example.controller;

import com.example.entity.User;
import com.example.util.DButil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //设置中文编码
        req.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type", "text/html;charset=utf-8");

        //使用request来接收用户通过浏览器传递过来的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");

        //将user数据，封装到User实体类中
        User user = new User(username, password, email);

        //将用户注册信息，存入数据库当中（模拟数据库）
        DButil database = DButil.getInstance();
        boolean result = database.insertUser(user);

        //判断是否注册成功
        if (!result) {
            //注册失败
            //传递错误信息
            req.setAttribute("DBmsq", "你注册的用户已存在！");
            //跳转
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        }

        //注册成功
        resp.getWriter().println("恭喜你，注册成功，该页面将在3秒后进行跳转！");

        //将用户信息存入session，以便后续使用
        req.getSession().setAttribute("user", user);

        //3秒后跳转
        resp.setHeader("refresh", "3;url=/success.jsp");
    }
}
